/*
Copyright (c) [2019年5月1日] [吴超]
[MBT_studio] is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
#include "stdafx.h"
#include "lua语法解析.h"


static const BlockPair block_pairs[] = {
	{"if",       "end",   BLOCK_IF},
	{"for",      "end",   BLOCK_FOR},
	{"while",    "end",   BLOCK_WHILE},
	{"function", "end",   BLOCK_FUNCTION},
	{"do",       "end",   BLOCK_DO},
	{"repeat",   "until", BLOCK_REPEAT},
	{"{",        "}",     BLOCK_TABLE}
};

// 检查字符是否为Lua标识符的分隔符
static bool is_delimiter(char c) {
	return isspace(c) || c == '(' || c == ')' || c == '{' || c == '}' 
		|| c == ';' || c == ',' || c == '=' || c == '+' || c == '-' 
		|| c == '*' || c == '/' || c == '%' || c == '^' || c == '<' 
		|| c == '>' || c == '!' || c == '&' || c == '|' || c == ':';
}

const std::string g代码块关键字[] = {"if", "for", "while", "function", "do", "repeat", "local", "return"};

enum E_State {
	STATE_NORMAL,        // 正常状态
	STATE_STRING_SINGLE, // 单引号字符串内
	STATE_STRING_DOUBLE, // 双引号字符串内
	STATE_COMMENT_LINE,  // 单行注释
	STATE_COMMENT_BLOCK  // 多行注释
};

bool f_lua_语法快检测(const std::string& code) {
	std::stack<BlockType> block_stack;
	size_t pos = 0;
	const size_t len = code.size();

	E_State state = STATE_NORMAL;

	while (pos < len) {
		switch (state) {
			case STATE_NORMAL: {
				// 检查多行注释开始
				if (pos + 3 < len && code[pos] == '-' && code[pos+1] == '-' 
					&& code[pos+2] == '[' && code[pos+3] == '[') {
					state = STATE_COMMENT_BLOCK;
					pos += 4;
					continue;
				}
				// 检查单行注释开始
				if (pos + 1 < len && code[pos] == '-' && code[pos+1] == '-') {
					state = STATE_COMMENT_LINE;
					pos += 2;
					continue;
				}
				// 检查字符串开始
				if (code[pos] == '\'') {
					state = STATE_STRING_SINGLE;
					pos++;
					continue;
				}
				if (code[pos] == '"') {
					state = STATE_STRING_DOUBLE;
					pos++;
					continue;
				}
				// 检查语法块开始关键字
				bool found = false;
				for (const auto &pair : block_pairs) {
					size_t start_len = strlen(pair.start);
					if (pos + start_len <= len && code.substr(pos, start_len) == pair.start 
						&& (pos == 0 || is_delimiter(code[pos-1])) 
						&& (pos + start_len == len || is_delimiter(code[pos + start_len]))) {
						block_stack.push(pair.type);
						pos += start_len;
						found = true;
						break;
					}
				}
				if (found) break;
				// 检查语法块结束关键字
				for (const auto &pair : block_pairs) {
					size_t end_len = strlen(pair.end);
					if (pos + end_len <= len && code.substr(pos, end_len) == pair.end 
						&& (pos == 0 || is_delimiter(code[pos-1])) 
						&& (pos + end_len == len || is_delimiter(code[pos + end_len]))) {
						if (block_stack.empty() || block_stack.top() != pair.type) {
							return false;
						}
						block_stack.pop();
						pos += end_len;
						found = true;
						break;
					}
				}
				if (found) break;
				pos++;
				break;
			}

			case STATE_STRING_SINGLE:
				if (code[pos] == '\\' && pos + 1 < len) {
					pos += 2;
				} else if (code[pos] == '\'') {
					state = STATE_NORMAL;
					pos++;
				} else {
					pos++;
				}
				break;

			case STATE_STRING_DOUBLE:
				if (code[pos] == '\\' && pos + 1 < len) {
					pos += 2;
				} else if (code[pos] == '"') {
					state = STATE_NORMAL;
					pos++;
				} else {
					pos++;
				}
				break;

			case STATE_COMMENT_LINE:
				if (code[pos] == '\n' || code[pos] == '\r') {
					state = STATE_NORMAL;
				}
				pos++;
				break;

			case STATE_COMMENT_BLOCK:
				if (pos + 1 < len && code[pos] == ']' && code[pos+1] == ']') {
					state = STATE_NORMAL;
					pos += 2;
				} else {
					pos++;
				}
				break;
		}
	}

	return block_stack.empty() && state == STATE_NORMAL;
   
}

static bool f_代码块是否包含关键字(const std::string& code) {

}
bool f_lua_是否为单个变量(const std::string& code) {
	static const std::vector<std::string> keywords = {
		"and", "break", "do", "else", "elseif", "end", "false", "for",
		"function", "if", "in", "local", "nil", "not", "or", "repeat",
		"return", "then", "true", "until", "while", "="
	};

	//std::find(code.begin(), code.end(), keywords);
	for (const auto& kw : keywords) {
		if(code.find(kw) != std::string::npos) return false;
	}
	return true;
}

bool f_lua_是否为表达式(const std::string &code) {
	
	if (code.find("function ") != std::string::npos) return false;
	if (code.find("local ") != std::string::npos) return false;
	if (code.find("local ") != std::string::npos) return false;
	if (code.find("=") != std::string::npos) return false;
	// 检查是否包含常见运算符
	//const std::string ops = "+-*/%^#<>=";
	//for (char c : code) {
	//	if (ops.find(c) != std::string::npos) {
	//		return true;
	//	}
	//}
	std::string trimmed = code;
	trimmed.erase(0, trimmed.find_first_not_of(" \t\n\r"));
	trimmed.erase(trimmed.find_last_not_of(" \t\n\r") + 1);

	
	for (const auto &kw : g代码块关键字) {
		size_t pos = code.find(kw);
		if (pos != std::string::npos && 
			(pos == 0 || is_delimiter(trimmed[pos-1])) &&
			(pos + kw.size() == trimmed.size() || is_delimiter(trimmed[pos + kw.size()]))) {
			return false;
		}
	}
	//if (code.find('=') != std::string::npos && code.find("==") == std::string::npos) {
	//	return false;
	//}

	return true;
}

bool f_lua_基础语法检查(const std::string& code) {
	// 过滤空代码
	std::string trimmed = code;
	trimmed.erase(0, trimmed.find_first_not_of(" \t\n\r"));
	trimmed.erase(trimmed.find_last_not_of(" \t\n\r") + 1);
	if (trimmed.empty()) return false;

	// 检查无效字符（仅允许Lua语法支持的字符）
	//const std::string valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_+-*/%^=<>!(){}[].,;: \t\n\r\"'";
	//for (char c : code) {
	//	if (valid_chars.find(c) == std::string::npos) {
	//		return false;  // 包含无效字符
	//	}
	//}

	// 检查字符串是否闭合（基础语法检查）
	enum State { NORMAL, STRING_SINGLE, STRING_DOUBLE };
	State state = NORMAL;
	for (char c : code) {
		switch (state) {
			case NORMAL:
				if (c == '\'') state = STRING_SINGLE;
				else if (c == '"') state = STRING_DOUBLE;
				break;
			case STRING_SINGLE:
				if (c == '\\' && &c != &code.back()) continue;  // 跳过转义符
				else if (c == '\'') state = NORMAL;
				break;
			case STRING_DOUBLE:
				if (c == '\\' && &c != &code.back()) continue;
				else if (c == '"') state = NORMAL;
				break;
		}
	}
	return state == NORMAL;  // 确保所有字符串已闭合
}

bool f_lua_是否为声明(const std::string& code) {
	size_t pos = 0;
	const size_t len = code.size();


	//while (pos < len) {
	//	switch (state) {
	//	}
	//}

	return false;
}


//std::string f_lua_加载编译代码(lua_State* L, const std::string& code) {
//	if (code.empty()) return false;
//	if (!f_lua_语法快检测(code)) {
//		return false;
//	}
//	int32 status = luaL_loadstring(L, code.c_str());
//	if (status == LUA_OK) {
//		lua_pop(L, 1);
//		return true;
//	}
//	const char *err = lua_tostring(L, -1);
//	bool is_incomplete = (std::string(err).find("unfinished") != std::string::npos) 
//		|| (std::string(err).find("near '<eof>'") != std::string::npos)
//		|| (std::string(err).find("expected") != std::string::npos);
//	lua_pop(L, 1);
//	return !is_incomplete;
//}


E_代码解析状态 f_check_syntax_validity(const std::string& full_code, S_ParseContext& context) {
	// 重置上下文状态
	//context.in_single_quote = false;
	//context.in_double_quote = false;
	//context.in_multi_comment = false;
	//while (!context.block_stack.empty()) context.block_stack.pop();
	//
	//// 内部解析状态
	//enum 内部状态 {
	//	正常, 单引号内, 双引号内, 单行注释内, 多行注释内
	//};
	//内部状态 当前状态 = 正常;
	//
	//const size_t code_length = full_code.size();
	//size_t pos = 0;
	//
	//// 遍历整个字符串的每个字符
	//while (pos < code_length) {
	//	char current_char = full_code[pos];
	//
	//	switch (当前状态) {
	//		case 正常:
	//			// 检查多行注释开始（--[[）
	//			if (pos + 3 < code_length && 
	//				full_code[pos] == '-' && full_code[pos+1] == '-' &&
	//				full_code[pos+2] == '[' && full_code[pos+3] == '[') {
	//				当前状态 = 多行注释内;
	//				pos += 4;
	//				continue;
	//			}
	//			// 检查单行注释开始（--）
	//			if (pos + 1 < code_length && 
	//				full_code[pos] == '-' && full_code[pos+1] == '-') {
	//				当前状态 = 单行注释内;
	//				pos += 2;
	//				continue;
	//			}
	//			// 检查单引号字符串开始
	//			if (current_char == '\'') {
	//				当前状态 = 单引号内;
	//				pos++;
	//				continue;
	//			}
	//			// 检查双引号字符串开始
	//			if (current_char == '"') {
	//				当前状态 = 双引号内;
	//				pos++;
	//				continue;
	//			}
	//
	//			// 检查代码块开始关键字
	//			bool block_found = false;
	//			for (const auto& block : block_pairs) {
	//				size_t keyword_len = strlen(block_start_keyword);
	//				if (pos + keyword_len <= code_length) {
	//					bool match = true;
	//					for (size_t i = 0; i < keyword_len; i++) {
	//						if (full_code[pos + i] != block.start_keyword[i]) {
	//							match = false;
	//							break;
	//						}
	//					}
	//					if (match && 
	//						(pos == 0 || is_delimiter(full_code[pos-1])) &&
	//						(pos + keyword_len == code_length || is_delimiter(full_code[pos + keyword_len]))) {
	//
	//						context.block_stack_stack.push(block.type);
	//						pos += keyword_len;
	//						block_found = true;
	//						break;
	//					}
	//				}
	//			}
	//			if (block_found) break;
	//
	//			// 检查代码块结束关键字
	//			for (const auto& block : block_list) {
	//				size_t keyword_len = strlen(block.end_keyword);
	//				if (pos + keyword_len <= code_length) {
	//					bool match = true;
	//					for (size_t i = 0; i < keyword_len; i++) {
	//						if (full_code[pos + i] != block.end_keyword[i]) {
	//							match = false;
	//							break;
	//						}
	//					}
	//					if (match && 
	//						(pos == 0 || is_delimiter(full_code[pos-1])) &&
	//						(pos + keyword_len == code_length || is_delimiter(full_code[pos + keyword_len]))) {
	//
	//						if (context.block_stack.empty() || context.block_stack.top() != block.type) {
	//							return E_代码解析状态::e_语法错误;
	//						}
	//						context.block_stack.pop();
	//						pos += keyword_len;
	//						block_found = true;
	//						break;
	//					}
	//				}
	//			}
	//			if (block_found) break;
	//
	//			// 检查无效字符
	//			if (!isalnum(current_char) && !is_operator(current_char) && !is_delimiter(current_char)) {
	//				return E_代码解析状态::e_语法错误;
	//			}
	//			pos++;
	//			break;
	//
	//		case 单引号内:
	//			if (current_char == '\\' && pos + 1 < code_length) pos++;
	//			else if (current_char == '\'') 当前状态 = 正常;
	//			pos++;
	//			break;
	//
	//		case 双引号内:
	//			if (current_char == '\\' && pos + 1 < code_length) pos++;
	//			else if (current_char == '"') 当前状态 = 正常;
	//			pos++;
	//			break;
	//
	//		case 单行注释内:
	//			if (current_char == '\n') {
	//				当前状态 = 正常;
	//			}
	//			pos++;
	//			break;
	//
	//		case 多行注释内:
	//			if (pos + 1 < code_length && full_code[pos] == ']' && full_code[pos+1] == ']') {
	//				当前状态 = 正常;
	//				pos += 2;
	//			} else {
	//				pos++;
	//			}
	//			break;
	//	}
	//}
	//
	//// 更新上下文状态
	//context.in_single_quote = (当前状态 == 单引号内);
	//context.in_double_quote = (当前状态 == 双引号内);
	//context.in_multi_comment = (当前状态 == 多行注释内);
	//
	//// 判断代码是否完整
	//if (context.in_single_quote || context.in_double_quote || 
	//	context.in_multi_comment || !context.block_stack.empty()) {
	//	return E_代码解析状态::e_语法不完整;
	//}
	return E_代码解析状态::e_语法正确且完整;
}





Inline bool isAllWhitespace(const std::string& str) {
	return std::all_of(str.begin(), str.end(), ::isspace);
}

// 提取错误信息核心内容
static std::string getErrorContent(const std::string& error) {
	
	std::string errorContent;
	size_t lastColon = error.find_last_of(":");
	if (lastColon != std::string::npos) {
		errorContent = error.substr(lastColon + 1);
		size_t start = errorContent.find_first_not_of(" \t");
		if (start != std::string::npos) {
			errorContent = errorContent.substr(start);
		}
	} else {
		errorContent = error;
	}

	std::transform(errorContent.begin(), errorContent.end(), 
				   errorContent.begin(), ::tolower);

	return errorContent;
}

// 检查代码是否处于不完整的结构中
static bool isInIncompleteStructure(const std::string& code) {
	int parenBalance = 0;    // 圆括号平衡
	int braceBalance = 0;    // 花括号平衡
	int bracketBalance = 0;  // 方括号平衡
	bool inString = false;   // 是否在字符串中
	char stringType = '\0';  // 字符串类型（'或"）
	bool inComment = false;  // 是否在单行注释中
	bool inLongComment = false; // 是否在长注释中

	for (size_t i = 0; i < code.size(); ++i) {
		char c = code[i];

		// 处理长注释
		if (inLongComment) {
			if (c == ']' && i + 1 < code.size() && code[i+1] == ']') {
				inLongComment = false;
				i++; // 跳过第二个]
			}
			continue;
		}

		// 处理单行注释
		if (inComment) {
			if (c == '\n') {
				inComment = false;
			}
			continue;
		}

		// 处理字符串
		if (inString) {
			if (c == stringType) {
				// 检查转义字符
				if (i == 0 || code[i-1] != '\\') {
					inString = false;
				}
			}
			continue;
		}

		// 检查注释
		if (c == '-' && i + 1 < code.size()) {
			if (code[i+1] == '-') {
				inComment = true;
				i++;
				continue;
			} else if (code[i+1] == '[') {
				inLongComment = true;
				i++;
				continue;
			}
		}

		// 检查字符串开始
		if (c == '"' || c == '\'') {
			inString = true;
			stringType = c;
			continue;
		}

		// 检查括号
		if (c == '(') parenBalance++;
		else if (c == ')') parenBalance--;
		else if (c == '{') braceBalance++;
		else if (c == '}') braceBalance--;
		else if (c == '[') bracketBalance++;
		else if (c == ']') bracketBalance--;

		// 平衡不能为负（这是语法错误）
		if (parenBalance < 0 || braceBalance < 0 || bracketBalance < 0) {
			return false;
		}
	}

	// 如果有未闭合的结构或处于字符串/注释中，说明需要继续输入
	return (parenBalance > 0 || braceBalance > 0 || bracketBalance > 0 ||
			inString || inComment || inLongComment);
}

// 辅助函数：处理交互式输入特有的错误信息
bool f_lua_互式输入特有的错误信息(const std::string& error, const std::string& code) {
	
	// 首先检查是否有未闭合的结构
	if (isInIncompleteStructure(code)) {
		return true;
	}

	auto errorStr = getErrorContent(error);

	// 明确需要继续输入的模式（模糊匹配）
	const std::set<std::string> continuationPatterns = {
		"unexpected end of",       // 意外结束（如unexpected end of input）
		"incomplete statement",    // 语句不完整
		"unfinished string",       // 字符串未结束
		"unfinished comment",      // 注释未结束
		"unfinished long comment", // 长注释未结束
		"expecting",               // 期望更多元素
		"<eof>",                   // 在文件结束处
		"missing 'end'",           // 缺少end
		"unclosed",                // 未闭合的结构
		"no matching",             // 没有匹配的闭合符
		"unterminated",            // 未终止的结构
		"'<name>' expected near '('", // 函数名缺失
		"function definition expected" // 函数定义不完整
	};

	// 需要排除的错误模式（这些是真正的语法错误）
	const std::set<std::string> errorPatterns = {
		"unexpected 'end'",        // 多余的end
		"unexpected symbol",       // 意外的符号（如你提供的案例）
		"unexpected token",        // 意外的标记
		"unexpected character",    // 意外的字符
		"syntax error"             // 明确的语法错误
	};

	// 先检查是否是明确的错误模式
	for (const auto& pattern : errorPatterns) {
		if (errorStr.find(pattern) != std::string::npos) {
			return false; // 明确的错误，不需要继续输入
		}
	}

	// 再检查是否是需要继续输入的模式
	for (const auto& pattern : continuationPatterns) {
		if (errorStr.find(pattern) != std::string::npos) {
			return true;
		}
	}

	// 控制结构不完整检查
	std::vector<std::string> controlStructures = {"if", "for", "while", "repeat", "function"};
	for (const auto& str : controlStructures) {
		if (code.find(str) != std::string::npos && 
			code.find("end") == std::string::npos) {
			return true;
		}
	}

	return false;
}







